# coding:utf-8
import selectors
import socket


sel = selectors.DefaultSelector()


def accept(sock, mask):
    conn, addr = sock.accept()   # should be ready
    print('accepted', conn, 'from', addr)
    conn.setblocking(False)
    sel.register(conn,selectors.EVENT_READ, read)   # 新连接注册read回调函数


def read(conn, mask):
    data = conn.recv(1000)   # Should be ready
    if data:
        print('echoing', repr(data), 'to', conn)
        conn.send(data)  # Hope it won't block
    else:
        print('closing', conn)
        sel.unregister(conn)
        conn.close()


def main():
    sock = socket.socket()
    sock.bind(('localhost', 9999))
    sock.listen(100)
    sock.setblocking(False)
    sel.register(sock,selectors.EVENT_READ,accept)

    while True:
        events = sel.select()  # 默认阻塞,有活动连接就返回活动的连接列表
        for key, mask in events:
            callback = key.data  # accept
            callback(key.fileobj,mask)  # key.fileobj= 第一次是文件句柄socket实例 conn
    pass


if __name__ == '__main__':
    main()